﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;

namespace Hotel.OTA.Service.Common.Utility
{
    public static class AESHelper
    {
        public static string Encrypt(string encryptStr, string password)
        {
            byte[] data = Encoding.UTF8.GetBytes(encryptStr);
            using (RijndaelManaged rm = CreateRM(password))
            {
                using (ICryptoTransform transform = rm.CreateEncryptor())
                {
                    byte[] result = transform.TransformFinalBlock(data, 0, data.Length);
                    return Convert.ToBase64String(result, 0, result.Length);
                }
            }
        }

        public static string Decrypt(string decryptStr, string password)
        {
            byte[] data = Convert.FromBase64String(decryptStr);
            using (RijndaelManaged rm = CreateRM(password))
            {
                using (ICryptoTransform transform = rm.CreateDecryptor())
                {
                    byte[] result = transform.TransformFinalBlock(data, 0, data.Length);
                    return Encoding.UTF8.GetString(result);
                }
            }
        }

        public static string GetMd5String(string sourceString)
        {
            using (MD5 hash = MD5.Create())
            {
                byte[] strRes = hash.ComputeHash(Encoding.UTF8.GetBytes(sourceString));
                StringBuilder sb = new StringBuilder();
                foreach (byte str in strRes)
                {
                    sb.AppendFormat("{0:X2}", str);
                }

                return sb.ToString();
            }
        }

        private static RijndaelManaged CreateRM(string password)
        {
            string key = GetMd5String(password);    // 使用MD5算法，将KEY统一为32位长度字符串
            string iv = key.Substring(8, 16);       // IV为Key中截取中间的16位字符  

            RijndaelManaged rm = new RijndaelManaged();
            rm.Key = Encoding.UTF8.GetBytes(key);   // 统一使用UTF8进行编码，得到256位Key  
            rm.IV = Encoding.UTF8.GetBytes(iv);     // 得到128位IV
            rm.Mode = CipherMode.CBC;
            rm.Padding = PaddingMode.PKCS7;

            return rm;
        }
    }
}
